package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBulider;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;
    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Transactional
//    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer id) throws TesseractException, IOException {
        //1. 查询自媒体的文章数据 如果没有文章或者文章的状态不太则抛出异常
        WmNews wmNews = wmNewsMapper.selectById(id);

        if(null == wmNews || !wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2. 从文章中找到所有的图片和文本内容
        Map<String,Object> data = handleTextAndImages(wmNews);

        //2.1 先使用自定义的DFA算法审核 审核通过在调用阿里云
        boolean flag = handleSensitiveScan(data.get("content").toString(), wmNews);
        if(!flag) return;

        //3. 调用阿里云接口进行文章审核 如果审核失败则更新文章的状态位2 或者3 审核结束
        flag = handleTextScan(data.get("content").toString(), wmNews);
        if(!flag) return;

        //4. 从minio中下载所有的图片 并上传到阿里云进行图片审核 如果审核失败则更新文章的状态位2 或者3 审核结束
        flag = handleImageScan((List<String>) data.get("images"), wmNews);
        if(!flag) return;

        //5. 通过feign接口把自媒体的数据同步到文章微服务并返回文章微服务的文章id
        ResponseResult responseResult = saveAppArticle(wmNews);
        if(!"200".equals(responseResult.getCode().toString())){
            throw new CustomException(AppHttpCodeEnum.TRANS_ARCICLE_FAIL);
        }

        //6. 如果都成功了则更新审核状态位9 并填充文章微服务的文章id到自媒体的文章表
        wmNews.setArticleId(Long.parseLong(responseResult.getData().toString()));
        updateWmNes(wmNews, WmNews.Status.PUBLISHED.getCode(), "审核通过");
    }

    /**
     * DFA算法审核
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        List<WmSensitive> sensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> list = sensitiveList.stream().map(sensitive -> sensitive.getSensitives()).collect(Collectors.toList());

        //初始化DFA算法的大的map
        SensitiveWordUtil.initMap(list);

        //通过DFA算法审核内容
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(null != map && map.size() > 0){
            flag = false;
            updateWmNes(wmNews, WmNews.Status.FAIL.getCode(), "文本中包含了自定义的敏感词=" + map);
        }

        return flag;
    }

    /**
     * 通过feign接口同步数据到文章微服务
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        /*ArticleDto dto = new ArticleDto();

        BeanUtils.copyProperties(wmNews, dto);
        //文章的布局
        dto.setLayout(wmNews.getType());

        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }

        dto.setCreatedTime(new Date());*/

        ArticleDto dto = ArticleDtoBulider
                .builder(wmNews, wmChannelMapper, wmUserMapper)
                .basicCopy()
                .buildBasic()
                .buildWmChannel()
                .buildWmUser()
                .build();

        ResponseResult responseResult = articleClient.save(dto);
        return responseResult;
    }

    /**
     * 图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) throws IOException, TesseractException {
        boolean flag = true;
        if(null == images || images.size() == 0){
            //表示当前的文章内容中没有图片 封面没有图片
            return flag;
        }

        //存储所有图片的二进制
        //下载之前对图片进行去重
        images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList = new ArrayList<>();
        for (String url : images) {
            //下载图片
            byte[] bytes = fileStorageService.downLoadFile(url);
            //对每一张图片进行识别 得到文字 然后用DFA算法审核一次
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(inputStream);
            String result = tess4jClient.doOCR(image);
            flag = handleSensitiveScan(result, wmNews);
            if(!flag) return  flag;

            imageList.add(bytes);
        }

        Map map = null;
        try {
            map = greenImageScan.imageScan(imageList);
            if(null != map && map.size() > 0){
                Object suggestion = map.get("suggestion");
                if(suggestion.equals("block")){
                    //审核失败
                    flag = false;
                    //更新文章的审核状态
                    updateWmNes(wmNews, WmNews.Status.FAIL.getCode(), "图片中包含了规格词");
                }else if(suggestion.equals("review")){
                    flag = false;
                    updateWmNes(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片中包含了不确定的内容需要人工审核");
                }
            }
        } catch (Exception e) {
            flag = false;
            updateWmNes(wmNews, WmNews.Status.FAIL.getCode(), "图片调用审核接口失败了");
        }


        return flag;
    }

    /**
     * 文本审核
     * @param content
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;

        try {
            Map map = greenTextScan.greeTextScan(content);
            if(null != map && map.size() > 0){
                Object suggestion = map.get("suggestion");
                if(suggestion.equals("block")){
                    flag =false;
                    //修改文章的审核状态位2
                    updateWmNes(wmNews, WmNews.Status.FAIL.getCode(), "文本中包含了违规词");
                }else if(suggestion.equals("review")){
                    flag = false;
                    //修改文章的审核状态位3
                    updateWmNes(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文本中包含了不确定的词需要人工审核");
                }
            }

        } catch (Exception e) {
            flag = false;
            updateWmNes(wmNews, WmNews.Status.FAIL.getCode(), "调用审核接口失败了");
        }

        return flag;
    }

    private void updateWmNes(WmNews wmNews, short status, String reson) {
        wmNews.setStatus(status);
        wmNews.setReason(reson);

        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从文章中找到所有的图片和文本
     *  content: 所有的文本内容
     *  images: 所有的图片的url地址
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        StringBuilder sb = new StringBuilder(); //保存文本内容
        List<String> images = new ArrayList<>(); //保存图片内容

        sb.append(wmNews.getTitle()); //拼接文章的标题

        List<Map> mapList = JSONArray.parseArray(wmNews.getContent(), Map.class);
        for (Map map : mapList) {
            if("text".equals(map.get("type"))){
                sb.append("-").append(map.get("value").toString()); // 内容中的文本
            }else if("image".equals(map.get("type"))){
                images.add(map.get("value").toString()); // 内容中的图片
            }
        }

        //加上封面中的图片
        String imageUrl = wmNews.getImages();
        if(StringUtils.isNotEmpty(imageUrl)){
            Collections.addAll(images, imageUrl.split(","));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("content", sb.toString());
        map.put("images", images);

        return map;
    }
}
